<?php
class user extends Base_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->model ('user_m');
		//表单验证类
		$this->load->library('form_validation');
	}
	
	//登陆
	public function dologin(){
		//print_r($_POST);
	}
	
	//退出登陆
	public function logout ()
	{
		$this->session->sess_destroy();
	
		$this->load->helper('cookie');
		delete_cookie('uid');
		delete_cookie('username');
		delete_cookie('group_type');
		delete_cookie('gid');
		delete_cookie('openid');
		redirect('home/user/login');
	}
	
	public function login(){
		  
		//parse_str($_SERVER['QUERY_STRING'], $_GET);
		//print_r($_GET);
		//echo base_url('static/common/js/test.js');
		///echo 'home/login/test';
		//echo $id;
		//echo 9999;
		//$ttt=$this->uri->_fetch_uri_string();
		//echo $ttt;
		//print_r($this->uri);
		
		//$this->uri->_detect_uri();
		//$this->uri->get_detect_uri();
		//echo $this->uri->uri_string;
		
		//$ttt=preg_replace("|/*(.+?)/*$|", "\\1",$_SERVER['REQUEST_URI']);
		//print_r($ttt);
		
		if($this->auth->is_login()){
			//redirect();
		}
		$data['title'] = '用户登录';
		//if($_POST && $this->form_validation->run() === TRUE){
		$params = $this->input->post ( null );
	    //取config中的$rules
	    $this->config->load('form_validation');
	    $rules=$this->config->item('user/login');
		if($_POST && !$this->form_validation->validform($params,$rules) === TRUE){
			
			$data = array(
					'username' => $this->input->post('username', TRUE),
					'password' => $this->input->post('password',TRUE)
			);
		
			if ($this->user_m->login($data)) {
				$uid=$this->session->userdata('uid');
				//更新积分
				if(time()-@$data['myinfo']['lastlogin']>86400){
					$this->config->load('userset');
					$this->user_m->update_credit($uid,$this->config->item('credit_login'));
				}
				
				$this->user_m->update_user($uid,array('lastlogin'=>time()));
				redirect();
			} else {
				echo ('用户名或密错误!');
				//show_message('用户名或密错误!');
			}
		} else {
			$data['csrf_name'] = $this->security->get_csrf_token_name();
			$data['csrf_token'] = $this->security->get_csrf_hash();
			//$this->load->view('login',$data);
			$this->display('user_login.html');
		}
		
		
		
	}
	
	//注册
public function register ()
	{
       //加载form类，为调用错误函数,需view前加载
      //\system\helpers\form_helper.php
      $this->load->helper('form');
      $this->load->helper('function');
		/*
		 * $this->load->library('session');
 
$this->load->model('hello_model');
 
$this->load->helper(array('url', 'array'));
 
$this->load->language(array('user_menu', 'user_tips'));
		 */
		
		//$this->load->library('session');
		//$this->load->library('auth');
		$data['title'] = '注册新用户';
		//$this->session->set_userdata('name','yang');
// 		if($this->session->userdata('uid')){
// 			echo('已登录，请退出再注册');
// 		}
		if ($this->auth->is_login()) {
			//show_message('已登录，请退出再注册',site_url());
			echo($this->session->userdata('uid'));
			echo('已登录，请退出再注册');
		}
		
		if($_POST){
			//验证参数
			$rules = array (                
					array (
					'field' => 'username',
					'label' => '用户名',
					'rules' => 'required',),
					array (
					'field' => 'email',
					'label' => '邮箱',
					'rules' => 'email',
					),
					array (
					'field' => 'password',
					'label' => '密码',
					'rules' => 'required',
					) );
			//字段
			$params = $this->input->post ( null );
			$error = $this->form_validation->validform($params,$rules);
			if($error != '') {
				echo $error;
				return;
			}
			//入库
			$password = $this->input->post('password',true);
			//生成盐 helper('function');
			$salt =get_salt();
			//载入config 下 userset   \system\core\Config.php
			$this->config->load('userset');//用户积分
			
			
			$data = array(
					'username' => strip_tags($this->input->post('username')),
					'password' => password_dohash($password,$salt),
					'salt' => $salt,
					'email' => $this->input->post('email',true),
					//取config下值  //初始加分
					'credit' => $this->config->item('credit_start'),
					'ip' => get_onlineip(),
					'group_type' => 2,
					'gid' => 3,
					'regtime' => time(),
					'is_active' => 1
			);
			if($this->user_m->register($data)){
				$uid = $this->db->insert_id();
				$newdata=array('username'=>$data['username'],'password'=>$password);
				//生成登陆seesion
				$this->user_m->login($newdata);
				//去除验证码session
				$this->session->unset_userdata('yzm');
				//发送注册邮件
				if($this->config->item('mail_reg')=='on'){
					$subject='欢迎加入'.$this->config->item('site_name');
					$message='欢迎来到 '.$this->config->item('site_name').' 论坛<br/>请妥善保管这封信件。您的帐户信息如下所示：<br/>----------------------------<br/>用户名：'.$data['username'].'<br/>论坛链接: '.site_url().'<br/>----------------------------<br/><br/>感谢您的注册！<br/><br/>-- <br/>'.$this->config->item('site_name');
					send_mail($data['email'],$subject,$message);
					//echo $this->email->print_debugger();
				}
				
			    $this->db->set('value',$uid,false)->where('item','last_uid')->update('site_stats');
				$this->db->set('value','value+1',false)->where('item','total_users')->update('site_stats');
				redirect();
			}
			
			//print_r($data);
		} else{
           // $data['csrf_name'] = $this->security->get_csrf_token_name();
            //$data['csrf_token'] = $this->security->get_csrf_hash();
			//$this->load->view('register',$data);
            $this->display('user_register.html');
		}
		
		
		die();
		//if($uid){echo('已登录，请退出再注册');}
		//表单验证    自动加载  application/config/form_validation.php
		if($_POST && $this->form_validation->run() === TRUE){
			$password = $this->input->post('password',true);
			$salt =get_salt();
			$this->config->load('userset');//用户积分
			$data = array(
				'username' => strip_tags($this->input->post('username')),
				'password' => password_dohash($password,$salt),
				'salt' => $salt,
				'email' => $this->input->post('email',true),
				'credit' => $this->config->item('credit_start'),
				'ip' => get_onlineip(),
				'group_type' => 2,
				'gid' => 3,
				'regtime' => time(),
				'is_active' => 1
			);
			if($this->user_m->register($data)){
				$uid = $this->db->insert_id();
				$newdata=array('username'=>$data['username'],'password'=>$password);
				$this->user_m->login($newdata);
				//去除验证码session
				$this->session->unset_userdata('yzm');
				//发送注册邮件
				if($this->config->item('mail_reg')=='on'){
					$subject='欢迎加入'.$this->config->item('site_name');
					$message='欢迎来到 '.$this->config->item('site_name').' 论坛<br/>请妥善保管这封信件。您的帐户信息如下所示：<br/>----------------------------<br/>用户名：'.$data['username'].'<br/>论坛链接: '.site_url().'<br/>----------------------------<br/><br/>感谢您的注册！<br/><br/>-- <br/>'.$this->config->item('site_name');
					send_mail($data['email'],$subject,$message);
					//echo $this->email->print_debugger();
				}
				$this->db->set('value',$uid,false)->where('item','last_uid')->update('site_stats');
				$this->db->set('value','value+1',false)->where('item','total_users')->update('site_stats');
				redirect();
			}

		} else{
           // $data['csrf_name'] = $this->security->get_csrf_token_name();
            //$data['csrf_token'] = $this->security->get_csrf_hash();
			//$this->load->view('register',$data);
            $this->display('user_register.html');
		}
	}
	
	

	public function index()
	{
		
		//echo 'index'; 
		$this->display('home.html');
		die();
		/** 检查登陆 */
		if(!$this->auth->is_admin())
		{
			show_message('非管理员或未登录',site_url('admin/login/do_login'));
		}
		$data['title'] = '管理后台';
		//统计
		$stats=$this->db->get('site_stats')->result_array();
		$data['stats']=array_column($stats, 'value', 'item');
		$data['last_user']=$this->db->select('username')->where('uid',@$data['stats']['last_uid'])->get('users')->row_array();
		$data['stats']['last_username']=@$data['last_user']['username'];
		
		//$redirect	= $this->auth->is_logged_in(false, false);
		$this->load->view('dashboard', $data);

			//redirect('dashboard');


	}

	public function do_login ()
	{
		/** 检查登陆 */
		if($this->auth->is_admin())
		{
			redirect('admin/login/index');
		}
		$data['title'] = '用户登录';
		if($_POST){
			$data = array(
                'username' => $this->input->post('username', TRUE),
                'password' => $this->input->post('password',TRUE)
            );
			if($this->user_m->login($data)){
				$uid=$this->session->userdata('uid');
				//更新积分
				$this->config->load('userset');
				$this->user_m->update_credit($uid,$this->config->item('credit_login'));
				//更新最后登录时间
				$this->user_m->update_user($uid,array('lastlogin'=>time()));
				redirect('admin/login/index');
				
			} else {
				show_message('用户名或密错误!');
			}
			$captcha = $this->input->post('captcha_code');
			if($this->config->item('show_captcha')=='on' && $this->session->userdata('yzm')!=$captcha) {
				show_message('验证码不正确');
			}
		} else {
			$data['csrf_name'] = $this->security->get_csrf_token_name();
        	$data['csrf_token'] = $this->security->get_csrf_hash();
			$this->load->view('do_login',$data);
		}
		
	}


	
}